package com.bitrate.dagger.server.websocket.auth;

import java.security.SecureRandom;

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;

/**
 * WebSocket Server 鉴权发号器
 */
public class Transmitter {

	public static final int SALT_SIZE = 8;

	/**
	 * 生成鉴权Token
	 * 
	 * @param seed
	 *            客户端约定好的截取固定位置长度的publicKey
	 */
	public static String genToken(String seed) {
		SecureRandom random = new SecureRandom();
		byte[] salt = new byte[SALT_SIZE];
		random.nextBytes(salt);
		byte[] hashToken = SecureUtil.hmacSha1(salt).digest(seed.getBytes());
		return HexUtil.encodeHexStr(salt) + HexUtil.encodeHexStr(hashToken);
	}

	/**
	 * @param verifySeed
	 *            待校验的Seed 服务器截取固定位置长度的publicKey
	 * @param token
	 *            客户端传入的Token
	 * @return 鉴权验证Token
	 */
	public static Boolean verify(String verifySeed, String token) {
		byte[] salt = HexUtil.decodeHex(token.substring(0, 16));
		byte[] verifyToken = SecureUtil.hmacSha1(salt).digest(
				verifySeed.getBytes());
		return token.equals(HexUtil.encodeHexStr(salt)
				+ HexUtil.encodeHexStr(verifyToken));
	}

}
